document.addEventListener('DOMContentLoaded', () => {
    const loginForm = document.querySelector('.login-form');
    const loginBtn = document.querySelector('.login-btn');

    // 检查是否已登录
    const token = localStorage.getItem('token');
    if (token) {
        // 如果已登录，直接跳转到游戏页面
        window.location.href = 'games.html';
        return;
    }

    // 添加登录按钮点击效果
    loginBtn.addEventListener('mousedown', (e) => {
        const rect = loginBtn.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        const ripple = document.createElement('div');
        ripple.style.left = `${x}px`;
        ripple.style.top = `${y}px`;
        ripple.className = 'ripple';
        
        loginBtn.appendChild(ripple);
        
        setTimeout(() => {
            ripple.remove();
        }, 1000);
    });

    // 处理表单提交
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        
        // 更改按钮状态
        loginBtn.disabled = true;
        loginBtn.innerHTML = '<span>登录中...</span>';
        
        try {
            const response = await fetch('http://localhost:3000/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username,
                    password
                })
            });

            const data = await response.json();

            if (response.ok) {
                // 登录成功
                showMessage('登录成功', 'success');
                // 存储token和用户信息
                if (data.token) {
                    localStorage.setItem('token', data.token);
                }
                if (data.user) {
                    localStorage.setItem('user', JSON.stringify(data.user));
                }
                
                // 延迟跳转，让用户看到成功消息
                setTimeout(() => {
                    window.location.href = 'games.html';
                }, 1000);
            } else {
                // 登录失败
                showMessage(data.message || '登录失败，请检查用户名和密码', 'error');
            }
        } catch (error) {
            console.error('登录错误:', error);
            showMessage('网络错误，请稍后重试', 'error');
        } finally {
            // 恢复按钮状态
            loginBtn.disabled = false;
            loginBtn.innerHTML = '<span>登录</span>';
        }
    });

    // 显示消息提示
    function showMessage(message, type) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}`;
        messageDiv.textContent = message;
        
        document.body.appendChild(messageDiv);
        
        // 3秒后移除消息
        setTimeout(() => {
            messageDiv.remove();
        }, 3000);
    }
}); 